<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="歌手名" prop="singerName">
        <el-input
          v-model="queryParams.singerName"
          placeholder="请输入歌手名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="singerGender">
        <el-select v-model="queryParams.singerGender" placeholder="请选择性别" clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in singerGenderJson"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['music:singer:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['music:singer:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['music:singer:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['music:singer:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="singerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="歌手编号" align="center" prop="singerId"/>-->
      <el-table-column label="歌手名" align="center" prop="singerName">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.singerName" placement="top">
            <div v-if="scope.row.singerName.length <= 4">{{ scope.row.singerName }}</div>
            <div v-if="scope.row.singerName.length > 4">{{ scope.row.singerName.substring(0, 4) }}...</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="singerImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.singerImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="singerDesc">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.singerDesc" placement="top">
            <div v-if="scope.row.singerDesc.length <= 3">{{ scope.row.singerDesc }}</div>
            <div v-if="scope.row.singerDesc.length > 3">{{ scope.row.singerDesc.substring(0, 3) }}...</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="省" align="center" prop="singerProvince" :formatter="convertCode"/>
      <el-table-column label="市" align="center" prop="singerCity" :formatter="convertCode"/>
      <el-table-column label="县" align="center" prop="singerRegion" :formatter="convertCode"/>
      <el-table-column label="详细地址" align="center" prop="singerAddress">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.singerAddress" placement="top">
            <div v-if="scope.row.singerAddress.length <= 3">{{ scope.row.singerAddress }}</div>
            <div v-if="scope.row.singerAddress.length > 3">{{ scope.row.singerAddress.substring(0, 3) }}...</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="出道日期" align="center" prop="singerDebutTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.singerDebutTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="性别" align="center" prop="singerGender">
        <template slot-scope="scope">
          <span>{{ getSingerGender(scope.row.singerGender) }}</span>
        </template>
      </el-table-column>

      <!--<el-table-column label="生日" align="center" prop="singerBirthday" width="180">-->
      <!--  <template slot-scope="scope">-->
      <!--    <span>{{ parseTime(scope.row.singerBirthday, '{y}-{m}-{d}') }}</span>-->
      <!--  </template>-->
      <!--</el-table-column>-->

      <el-table-column label="年龄" align="center">
        <template slot-scope="scope">
          <span>{{ calculateAge(scope.row.singerBirthday) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="singerRemark">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.singerRemark" placement="top">
            <div v-if="scope.row.singerRemark.length <= 3">{{ scope.row.singerRemark }}</div>
            <div v-if="scope.row.singerRemark.length > 3">{{ scope.row.singerRemark.substring(0, 3) }}...</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['music:singer:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['music:singer:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改歌手对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌手名" prop="singerName">
          <el-input v-model="form.singerName" placeholder="请输入歌手名"/>
        </el-form-item>
        <el-form-item label="描述" prop="singerDesc">
          <el-input v-model="form.singerDesc" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="省" prop="singerProvince">
          <el-select v-model="form.singerProvince" placeholder="请选择省" @change="refreshCity">
            <el-option
              v-for="item in areas"
              v-if="item.type === 1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="singerCity">
          <el-select v-model="form.singerCity" placeholder="请选择市" @change="refreshArea">
            <el-option
              v-for="item in areas"
              v-if="item.parentId === form.singerProvince"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="县" prop="singerRegion">
          <el-select v-model="form.singerRegion" placeholder="请选择县">
            <el-option
              v-for="item in areas"
              v-if="item.parentId === form.singerCity"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" prop="singerAddress">
          <el-input v-model="form.singerAddress" placeholder="请输入详细地址"/>
        </el-form-item>
        <el-form-item label="出道日期" prop="singerDebutTime">
          <el-date-picker clearable
                          v-model="form.singerDebutTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出道日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="性别" prop="singerGender">
          <el-select v-model="form.singerGender" placeholder="请选择性别">
            <el-option v-for="type in singerGenderJson" :label="type.label" :value="type.value" :key="type.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="singerBirthday">
          <el-date-picker clearable
                          v-model="form.singerBirthday"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="singerRemark">
          <el-input v-model="form.singerRemark" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="图片" prop="singerImg">
          <image-upload v-model="form.singerImg" placeholder="请上传图片"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listSinger, getSinger, delSinger, addSinger, updateSinger} from "@/api/music/singer";
import {parseTime} from "@/utils/ruoyi";
import areas from "@/utils/areas"
import {convertCode} from "../../../utils/areasUtil";

export default {
  name: "Singer",
  data() {
    return {
      areas: areas,
      singerGenderJson: [
        {value: 1, label: '男'},
        {value: 2, label: '女'},
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 歌手列表表格数据
      singerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        singerName: null,
        singerImg: null,
        singerDesc: null,
        singerProvince: null,
        singerCity: null,
        singerRegion: null,
        singerAddress: null,
        singerDebutTime: null,
        singerGender: null,
        singerBirthday: null,
        singerRemark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    convertCode,
    getSingerGender(gender) {
      const genderObj = this.singerGenderJson.find(item => `${item.value}` === `${gender}`);
      return genderObj ? genderObj.label : '未知';
    },
    refreshCity() {
      this.form.singerCity = '';
      this.form.singerRegion = '';
    },
    refreshArea() {
      this.form.singerRegion = '';
    },
    calculateAge(birthday) {
      const birthdayDate = new Date(birthday);
      if (isNaN(birthdayDate.getTime())) {
        console.error('Invalid date:', birthday);
        return '无效日期';
      }
      const today = new Date();
      let age = today.getFullYear() - birthdayDate.getFullYear();
      const m = today.getMonth() - birthdayDate.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < birthdayDate.getDate())) {
        age--;
      }
      return age;
    },
    parseTime,
    /** 查询歌手列表 */
    getList() {
      this.loading = true;
      listSinger(this.queryParams).then(response => {
        this.singerList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        singerId: null,
        singerName: null,
        singerImg: null,
        singerDesc: null,
        singerProvince: null,
        singerCity: null,
        singerRegion: null,
        singerAddress: null,
        singerDebutTime: null,
        singerGender: null,
        singerBirthday: null,
        singerRemark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.singerId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加歌手";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const singerId = row.singerId || this.ids
      getSinger(singerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改歌手";
        // 确保省、市、区的数据被正确设置
        this.form.singerProvince = this.form.singerProvince || ''; // 确保有默认值
        this.refreshCityList(); // 刷新市列表
        if (this.form.singerCity) {
          this.refreshDistrictList(); // 刷新区列表
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.singerId != null) {
            updateSinger(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSinger(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const singerIds = row.singerId || this.ids;
      this.$modal.confirm('是否确认删除歌手编号为"' + singerIds + '"的数据项？').then(function () {
        return delSinger(singerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('music/singer/export', {
        ...this.queryParams
      }, `singer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
